
package dk.unet.android.ll11;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

/**
 *
 * @author Nicolai Willems
 */
public class MapsActivity extends Activity{
    private LocationManager lm;
    private LocationListener locListener = new LocationListener() {

        private Location curLoc;

        public void onLocationChanged(Location newLoc) {
            if(curLoc == null){
                curLoc = newLoc;
            }else{
                //Decide wheter new location is better
                curLoc = this.isNewLocationBetter(newLoc);
            }

            //Make use of loc
            MapsActivity.this.updateDistanceToTSP(curLoc);
        }

        // Don't do anything
        public void onProviderDisabled(String arg0) { }
        public void onProviderEnabled(String arg0) { }
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) { }

        private Location isNewLocationBetter(Location newLoc){
            final int TWOMINUTES = 2*60*1000;

            long timeDelta = newLoc.getTime() - curLoc.getTime();
            boolean isNew = timeDelta > 0;
            int accuracyDelta = (int)(newLoc.getAccuracy() - curLoc.getAccuracy());

            // Time checking
            boolean isNewer = timeDelta > TWOMINUTES;

            // Accuracy checking
            boolean moreAccurate = accuracyDelta < 0;
            boolean lessAcurate = accuracyDelta > 0;

            // Provider checking
            String prov1 = curLoc.getProvider(), prov2 = newLoc.getProvider();
            boolean isSameProvider = (prov1 == null && prov2 == null) || prov1.equals(prov2);

            if((isNewer) ||
                    (moreAccurate) ||
                    (isNew && !lessAcurate) ||
                    (isNew && !(accuracyDelta > 200) && isSameProvider)){
                return newLoc;
            }
            return curLoc;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10, locListener);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 10, locListener);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(lm != null)
            lm.removeUpdates(locListener);
    }

    private void updateDistanceToTSP(Location loc){
        double tspLat = 55.679700, tspLon = 12.565667;
        Location tsp = new Location(LOCATION_SERVICE); tsp.setAccuracy(0);
        tsp.setLatitude(tspLat); tsp.setLongitude(tspLon);

        float result = loc.distanceTo(tsp);
        String toPrint = Float.toString(result) + " m's";
    }
}
